﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

using Happy.ExtentionMethods;

namespace Happy.Utils.IO
{
    /// <summary>
    /// 目录工具。
    /// </summary>
    public static class DirectoryUtil
    {
        /// <summary>
        /// 如果不存在就创建一个目录，返回目录的路径。
        /// </summary>
        public static string CreateDirectoryIfNotExists(string path)
        {
            path.MustNotEmpty("path");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            return path;
        }

        /// <summary>
        /// 先序遍历目录。
        /// </summary>
        public static void PreOrderTraverse(string path, Predicate<string> predicate, Action<string> action)
        {
            action.MustNotNull("action");

            if (!predicate(path))
            {
                return;
            }

            action(path);

            foreach (var item in Directory.GetDirectories(path))
            {
                PreOrderTraverse(item, predicate, action);
            }

            foreach (var item in Directory.GetFiles(path))
            {
                if (predicate(item))
                {
                    action(item);
                }
            }
        }
    }
}
